package net.davidlauzon.assemblandroid.models;

import java.util.ArrayList;
import java.util.Date;

import net.davidlauzon.assemblandroid.AssemblaAPIAdapter;
import net.davidlauzon.assemblandroid.exceptions.XMLParsingException;

public class Space {
	boolean canJoin = false;
	Date createdAt = null;
	String defaultShowpage = null;
	String description = null;
	String id = null;
	boolean isCommercial = false;
	boolean isManager = false;
	boolean isVolunteer = false;
	String name = null;
	String parentId = null;
	int publicPermissions = -1;
	int teamPermissions = -1;
	Date updatedAt = null;
	int watcherPermissions = -1;
	String wikiName = null;
	
	ArrayList<Ticket> tickets = null;
	
	public String id() { return this.id; }
	public String listItemText() { return this.name; }
	
	
	public Space(String id, String name, String description) {
		this.id = id;
		this.name = name;
		this.description = description;
	}
	
	/**
	 * WARNING: this methods caches the tickets on the first call.
	 * Use reloadTickets() if you want to make sure to have the latest data
	 * 
	 * @return ArrayList<Ticket> tickets
	 * @throws XMLParsingException 
	 */
	public ArrayList<Ticket> getTickets() throws XMLParsingException {
		if (! ticketsLoaded())
			reloadTickets();
		
		return tickets;
	}
	
	
	public ArrayList<Ticket> reloadTickets() throws XMLParsingException {
		tickets = AssemblaAPIAdapter.getInstance().getTicketsBySpaceId(this.id);
		return tickets;
	}
	
	/**
	 * @return true if records were already loaded
	 */
	public boolean ticketsLoaded() {
		return !(tickets == null);
	}

	public String name() { return this.name; }
	
	public String toString() {
		try {
			return "[Space] id = " + id + 
			" ; name = " + name +
			" ; description = " + description +
			" ; tickets = \n[" + getTickets() + "]";
		} catch (XMLParsingException e) {
			return "[Space] id = " + id + 
			" ; name = " + name +
			" ; description = " + description +
			" ; tickets = \n[" + "EXCEPTION raised while retrieving tickets" + "]";
		}
	}
	
}
